<?php

namespace weapp\ErxClose\behavior\user;

/**
 * 行为扩展
 */
class ErxCloseBehavior
{
    protected static $actionName;
    protected static $controllerName;
    protected static $moduleName;
    protected static $method;

    /**
     * 构造方法
     * @param Request $request Request对象
     * @access public
     */
    public function __construct()
    {
        !isset(self::$moduleName) && self::$moduleName = request()->module();
        !isset(self::$controllerName) && self::$controllerName = request()->controller();
        !isset(self::$actionName) && self::$actionName = request()->action();
        !isset(self::$method) && self::$method = strtoupper(request()->method());
    }

    /**
     * 模块初始化
     * @param array $params 传入参数
     * @access public
     */
    public function moduleInit(&$params)
    { 
        
    }

    /**
     * 操作开始执行
     * @param array $params 传入参数
     * @access public
     */
    public function actionBegin(&$params)
    {

    }

    /**
     * 视图内容过滤
     * @param array $params 传入参数
     * @access public
     */
    public function viewFilter(&$params)
    {        
        $data =  \think\Db::name('weapp')->where('code','ErxClose')->field('data')->find();
        $row = json_decode($data['data'], true);  
        if (!$row) {            
            return true;
        }                        
        // 全站
        if($row['is_open'] ==1){
            if(self::todo($row)==false){
                 $params=self::errhtml($row);
            }
        }       
        if($row['is_open']==2 && self::$controllerName =='Index' && self::$actionName=='index'){    
           if(self::todo($row)==false){
                $params=self::errhtml($row);
           }          
        }
    }
    /**
     * 应用结束
     * @param array $params 传入参数
     * @access public
     */
    public function appEnd(&$params)
    {

    }
    /**
     * 判断是否搜索引擎机器人或者爬行蜘蛛
     * @param 
     * @access public
     */    
    public function isRobot() {
        $agent= strtolower(isset($_SERVER['HTTP_USER_AGENT'])? $_SERVER['HTTP_USER_AGENT'] : '');
        if(!empty($agent)){
            $spiderSite= array(
                "TencentTraveler",
                "Baiduspider+",
                "BaiduGame",
                "Googlebot",
                "msnbot",
                "Sosospider+",
                "Sogou web spider",
                "ia_archiver",
                "Yahoo! Slurp",
                "YoudaoBot",
                "Yahoo Slurp",
                "MSNBot",
                "Java (Often spam bot)",
                "BaiDuSpider",
                "Voila",
                "Yandex bot",
                "BSpider",
                "twiceler",
                "Sogou Spider",
                "Speedy Spider",
                "Google AdSense",
                "Heritrix",
                "Python-urllib",
                "Alexa (IA Archiver)",
                "Ask",
                "Exabot",
                "Custo",
                "OutfoxBot/YodaoBot",
                "yacy",
                "SurveyBot",
                "legs",
                "lwp-trivial",
                "Nutch",
                "StackRambler",
                "The web archive (IA Archiver)",
                "Perl tool",
                "MJ12bot",
                "Netcraft",
                "MSIECrawler",
                "WGet tools",
                "larbin",
                "Fish search",
            );
            foreach($spiderSite as $val){
                $str = strtolower($val);
                    if(strpos($agent, $str) !== false){
                        return true;
                }
            }
        }
        return false;
    }
    /**
     * 提示文案
     * @param 
     * @access public
     */    
    public function errorhtml($text){
        if($text){        
            $content = htmlspecialchars_decode($text);
            $titlesource_html =<<<EOF
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <title></title>
            </head>
            <body>
            <div class="content">
            {$content}
            </div>
            </body>
            </html>
            EOF;
            return $titlesource_html;
        }
    }
    /**
     * 赦免自定义站点
     * @param 
     * @access public
     */
    public function links($row){
        $referer = $_SERVER['HTTP_REFERER'] ?? ''; // 获取Referer头信息
        $isFromFriendlyLink = false;            
        if($row){
            $allowed_domains = explode('|',$row['is_link']);                                                
            foreach ($allowed_domains as $domain) {
                if (strpos($referer, $domain) !== false) {
                    $isFromFriendlyLink = true;
                    break;
                }
            }         
            if ($isFromFriendlyLink) {
                return true;            
            } else {
                return false;
            }
        }else{
            return false;
        }
    }
    /**
     *  本地赦免站点
     * @param 
     * @access public
     */
    public function loclinks($data){        
        $referer ='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $isFromFriendlyLink = false;            
        $is_open_url =  nl2br($data['is_open_url']);
        if($data){
            $allowed_domains = explode('<br />',$is_open_url);
            foreach ($allowed_domains as $value) {
                $value =html_entity_decode($value);                
                if($value == $referer){
                    $isFromFriendlyLink = true;
                    break;
                }        
            }    
            if ($isFromFriendlyLink) {
                return true;            
            } else {
                return false;
            }
        }else{            
            return false;
        }
    }
    /**
     *  网站状态
     * @param 
     * @access public
     */
    public function errhtml($row){
        if(!$row){
            return false;
        }
        switch ($row['is_tig']) {
            case 1:
                // 提示文案
                $hml = self::errorhtml($row['content']);
                return $hml;
                break;
            case 2:
                // 404页面
                echo 2;
                break;
            case 3:
                // 404响应
                header('HTTP/1.1 404 Not Found');                
                $hml =<<<EOF
                <!DOCTYPE html>
                <html><head>
                <title>404 Not Found</title>
                </head><body>
                <h1>Not Found</h1>
                <p>The requested URL /2 was not found on this server.</p>
                <p>Additionally, a 404 Not Found
                error was encountered while trying to use an ErrorDocument to handle the request.</p>
                </body></html>
                EOF;
                return $hml;
                break;            
            default:                
                // 设置状态码为503，并发送状态头
                header('HTTP/1.1 503 Service Unavailable');
                // 可以输出一个简单的错误页面或者其他内容
                $hml =<<<EOF
                <!DOCTYPE html>
                <html><head>
                <title>503 Service Unavailable</title>
                </head><body>
                <h1>服务器暂时不可用，请稍后再试。</h1>                
                </body></html>
                EOF;                
                return $hml;                
                break;
        }
    }
    /**
     *  判断是否移动端
     * @param 
     * @access public
     */
    public function ismobile(){ 
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])){
            return true;
        } 
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA'])){ 
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
        } 
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])){
            $clientkeywords = array ('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'); 
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))){
                return true;
            } 
        } 
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])){ 
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))){
                return true;
            } 
        } 
        return false;
    }
    /**
     *  业务流程
     * @param 
     * @access public
     */
    public function todo($data){
        if($data['is_times']==1){ // 关闭时间段
            // 设置夜晚开始和结束的时间（小时和分钟）
            $nightStart = mktime($data['starttime'], 0); // 夜晚开始，晚上11点
            $nightEnd = mktime($data['endtime'], 0); // 夜晚结束，早上7点            
            // 获取当前服务器时间的时间戳
            $currentTime = time();             
            // 检查当前时间是否在夜晚时间内
            if ($currentTime >= $nightStart && $currentTime <= $nightEnd) {
                 $params = false;
            }else{
                 $params = true;
            }
        }elseif($data['is_seo']==1 && self::isRobot()){  // 允许蜘蛛爬虫
            $params = true;
        }elseif($data['is_dev']==1 && self::ismobile()){ // 允许移动端访问
            $params = true;
        }elseif(self::links($data)==true){ // 自定义赦免站点            
            $params = true;
        }elseif(self::loclinks($data)){ // 本地赦免网址
            $params = true;
        }else{            
            $params = false;
        }
        return $params;
    }
}